import { Etheme } from "@/types/common";
import { defineStore } from "pinia";
import { ref, watch } from "vue";
import { ExitType, ILocationData, ILockScreenData } from "@/types/system.ts";
import axios from "axios";

export const useSystem = defineStore(
  "system",
  () => {
    // 锁定设置
    let LockScreenData = ref<ILockScreenData>({
      password: "",
      securityQuestionList: [],
    });
    // 翻译提供商
    let TranslationProvider = ref("1");
    // 是否关闭前询问推出方式
    let IsRememberExitType = ref<boolean>(false);
    // 退出方式
    let WindowTabCloseType = ref<ExitType>(ExitType.Close);
    // 默认文件保存路径
    let DefaultDownloadPath = ref<string | null>(null);
    // 默认数据库路径
    let DateBasePath = ref<string | null>(null);
    // 主题
    let Theme = ref<Etheme>(Etheme.Light);
    // 用户定位信息
    let UserLocationData = ref<ILocationData>();
    let mediaQuery: MediaQueryList | null = null;

    watch(
      Theme,
      (newTheme) => {
        if (newTheme === Etheme.Os) {
          mediaQuery = window.matchMedia("(prefers-color-scheme: light)");
          document.documentElement.classList = mediaQuery.matches ? Etheme.Light : Etheme.Dark;
          mediaQuery.addEventListener("change", OsChangeTheme);
        } else {
          if (mediaQuery) {
            mediaQuery?.removeEventListener("change", OsChangeTheme);
            mediaQuery = null;
          }
          document.documentElement.classList = newTheme;
        }
      },
      { immediate: true },
    );

    // 系统主题切换
    function OsChangeTheme(e: MediaQueryListEvent) {
      document.documentElement.classList = e.matches ? Etheme.Dark : Etheme.Light;
    }

    // 获取用户定位信息
    async function GetUserLocation() {
      try {
        if (UserLocationData.value) return UserLocationData.value;
        const res = await axios.get(import.meta.env.VITE_UserLocationApi);
        if (res.status === 200) {
          UserLocationData.value = res.data;
        }
      } catch (e) {
        console.warn("获取定位失败", e);
      }
    }

    return {
      WindowTabCloseType,
      IsRememberExitType,
      TranslationProvider,
      DefaultDownloadPath,
      DateBasePath,
      LockScreenData,
      Theme,
      UserLocationData,
      GetUserLocation,
    };
  },
  {
    share: {
      enable: true,
      initialize: true,
    },
    localStore: {
      store: true,
    },
  },
);
